/**
 * HTTP请求封装
 * @Author: Abdusalam0126 2383624944@qq.com
 * @Date: 2025-08-05 15:46:14
 * @LastEditors: Abdusalam0126 2383624944@qq.com
 * @LastEditTime: 2025-08-05 15:57:12
 * @FilePath: src/utils/http.ts
 * @Description: HTTP请求封装工具
 */

// 基础配置
const BASE_URL = 'https://dev.aqilmini.com/api/v1'

// 响应数据接口
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 请求方法封装
const http = {
  /**
   * 获取请求头
   */
  getHeaders(): Record<string, string> {
    const token = uni.getStorageSync('token')
    return {
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {})
    }
  },

  /**
   * 处理响应
   */
  handleResponse<T>(res: any): Promise<T> {
    return new Promise((resolve, reject) => {
      if (res.statusCode === 200) {
        const data = res.data as ApiResponse<T>
        if (data.code === 200) {
          resolve(data.data)
        } else {
          // 显示错误信息
          uni.showToast({
            title: data.message || '请求失败',
            icon: 'none'
          })
          reject(new Error(data.message || '请求失败'))
        }
      } else {
        const errorMsg = res.data?.message || `请求失败(${res.statusCode})`
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
        reject(new Error(errorMsg))
      }
    })
  },

  /**
   * GET 请求
   * @param url 接口地址
   * @param params 请求参数
   */
  get<T>(url: string, params?: Record<string, any>): Promise<T> {
    return new Promise((resolve, reject) => {
      let fullUrl = BASE_URL + url
      
      // 添加查询参数
      if (params) {
        const queryString = Object.keys(params)
          .map(key => `${key}=${encodeURIComponent(params[key])}`)
          .join('&')
        fullUrl += `?${queryString}`
      }

      uni.request({
        url: fullUrl,
        method: 'GET',
        header: this.getHeaders(),
        success: (res) => {
          this.handleResponse<T>(res).then(resolve).catch(reject)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  /**
   * POST 请求
   * @param url 接口地址
   * @param data 请求数据
   */
  post<T>(url: string, data?: Record<string, any>): Promise<T> {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: 'POST',
        data,
        header: this.getHeaders(),
        success: (res) => {
          this.handleResponse<T>(res).then(resolve).catch(reject)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  /**
   * PUT 请求
   * @param url 接口地址
   * @param data 请求数据
   */
  put<T>(url: string, data?: Record<string, any>): Promise<T> {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: 'PUT',
        data,
        header: this.getHeaders(),
        success: (res) => {
          this.handleResponse<T>(res).then(resolve).catch(reject)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  /**
   * DELETE 请求
   * @param url 接口地址
   * @param data 请求数据
   */
  delete<T>(url: string, data?: Record<string, any>): Promise<T> {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: 'DELETE',
        data,
        header: this.getHeaders(),
        success: (res) => {
          this.handleResponse<T>(res).then(resolve).catch(reject)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  /**
   * 上传文件
   * @param url 接口地址
   * @param filePath 文件路径
   * @param name 文件字段名
   * @param formData 额外表单数据
   */
  upload<T>(url: string, filePath: string, name = 'file', formData?: Record<string, any>): Promise<T> {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token')
      const headers: Record<string, string> = {}
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }

      uni.uploadFile({
        url: BASE_URL + url,
        filePath,
        name,
        formData,
        header: headers,
        success: (res) => {
          try {
            const data = JSON.parse(res.data) as ApiResponse<T>
            if (data.code === 200) {
              resolve(data.data)
            } else {
              uni.showToast({
                title: data.message || '上传失败',
                icon: 'none'
              })
              reject(new Error(data.message || '上传失败'))
            }
          } catch (e) {
            console.error('解析响应数据失败:', e)
            uni.showToast({
              title: '解析响应数据失败',
              icon: 'none'
            })
            reject(new Error('解析响应数据失败'))
          }
        },
        fail: (err) => {
          console.error('上传失败:', err)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  }
}

export default http